#! /usr/bin/env python
# -*- coding: utf-8 -*-

import re
import os
import time
import random
import traceback

import FileHostProtoType

class fsitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, id, link, encrypt_name='', server_name=''): 
        #id save as D111111 or F1111111 
        FileHostProtoType.HostItem.__init__(self, name, type, id, link, encrypt_name, server_name)

class fso(FileHostProtoType.FileHostProcess):
    def __init__(self,user,pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "FileSonic"
        self._opener = None
        self._cj = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
    
    def login(self):
        '''
        login to FileSonic
        return opener object which includes cookies
        '''
        return True
    
    def find(self, filenames=[], filelist=None):
        '''
        open the filelist page according to opener with cookies
        '''
        found = []
        if filelist is None:
            filelist = self.getFileList()        
        filelistlower = [fl.server_name.lower() for fl in filelist]
        todel = []
        for fl in filenames:
            try:
                index = filelistlower.index(os.path.basename(fl).lower())
                found.append(filelist[index])
                todel.append(fl)
            except:
                continue
        for d in todel:
            filenames.remove(d)
        found.sort()
        return found
            
    def upload_web(self, file, progressLog=None, other_args=None):
        return self.upload_web_local(file, progressLog, other_args)    
    
    def upload_to_ftp(self, file, progressLog=None, other_args=None):
        url = 'ftp://ftp.filesonic.com' 
        userpwd = ('%s:%s' % (self._user, self._pwd)).encode('utf8')
        target_name = self.rename_func(file).encode('utf8')
        callback = None
        if progressLog is not None:
            callback = progressLog.write
            
        self.fherr.write("Uploading...%s" % file)
        times = 5
        while times > 0:
            try:
                self.upload_file_to_ftp(url, userpwd, file, target=target_name, callback=callback)
                break
            except:                
                self.fherr.write(traceback.format_exc())                
                times -= 1
                time.sleep(60)
                self.fherr.write('retry...')            
        
        item = fsitem(os.path.basename(file), 'file', 'NULL', 'NULL', self.rename_func(file))
        self.newupload.append(item)
        return item
    
if __name__ == "__main__":
    pass
